package hw_8_3.thread_demo5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketStation implements Runnable{
    private static int totalTickets = 100;
    private static final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            sellTicket(1,Thread.currentThread().getName());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void sellTicket(int ticketNum,String stationName ){
        lock.lock();
        try {
            if (totalTickets >= ticketNum){
                System.out.println(stationName + "售出" + ticketNum + "张票,剩余票数：" + totalTickets);
                totalTickets -= ticketNum;
            }
        } finally {
            lock.unlock();
        }
    }
}
